package com.zzyk.web.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.zzyk.main.configuration.exception.CustomException;
import com.zzyk.main.configuration.exception.UserException;
import com.zzyk.main.controller.BaseController;
import com.zzyk.main.model.dto.DeviceGroupDTO;
import com.zzyk.main.model.dto.ListUserDTO;
import com.zzyk.main.model.pojo.*;
import com.zzyk.main.model.vo.Message;
import com.zzyk.main.service.DeviceGroupService;
import com.zzyk.main.service.GroupDeviceService;
import com.zzyk.main.service.GroupUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wss_PC
 * @DESCRIPTION
 * @create 2021/1/5
 */
@RestController
@RequestMapping("/deviceGroup")
public class DeviceGroupController extends BaseController {
    @Resource
    private DeviceGroupService deviceGroupService;
    @Resource
    private GroupUserService groupUserService;
    @Resource
    private GroupDeviceService groupDeviceService;

    /**
     * 根据企业id数组查询分组
     *
     * @param ids
     * @return
     */
    @GetMapping("/getGroupByCompany")
    public Message getGroupByCompany(Integer[] ids) {
        return Message.success().addData("data", deviceGroupService.list(new LambdaQueryWrapper<DeviceGroup>().in(DeviceGroup::getOrganization, ids)));
    }

    /**
     * 删除设备分组
     *
     * @param group
     * @return
     */
    @GetMapping("/deleteDeviceGroup")
    @Transactional
    public Message deleteDeviceGroup(Integer group) {
        deviceGroupService.removeById(group);
        groupUserService.remove(new LambdaQueryWrapper<GroupUser>().eq(GroupUser::getGroup, group));
        groupDeviceService.remove(new LambdaQueryWrapper<GroupDevice>().eq(GroupDevice::getGroup, group));
        return Message.success();
    }

    /**
     * 根据设备分组和设备ID删除设备信息
     *
     * @param group
     * @param device
     * @return
     */
    @GetMapping("/deleteGroupDevice")
    public Message deleteGroupDevice(Integer group, Integer device) {
        return groupDeviceService.remove(new LambdaQueryWrapper<GroupDevice>().eq(GroupDevice::getGroup, group).eq(GroupDevice::getDevice, device)) ? Message.success() : Message.failed();
    }

    /**
     * 获取设备分组下的设备列表
     *
     * @param id
     * @param param
     * @return
     */
    @GetMapping("/getDeviceListByGroup")
    public Message getDeviceListByGroup(Integer id, String param) throws UserException {
        SysUser user = currentUser();
        List<GroupDevice> list = groupDeviceService.list(new LambdaQueryWrapper<GroupDevice>().eq(GroupDevice::getGroup, id));
        if (ObjectUtil.isNotNull(list) && !list.isEmpty()) {
            List<Integer> deviceIds = new ArrayList<>();
            for (GroupDevice groupDevice : list) {
                deviceIds.add(groupDevice.getDevice());
            }
            setPage();
            PageInfo<Device> info = new PageInfo<>(deviceGroupService.getDeviceList(deviceIds, param));
            return Message.success()
                    .addData("data", info.getList())
                    .addData("total", info.getTotal())
                    .addData("pages", info.getPages());
        }
        return Message.success()
                .addData("data", new ArrayList<GroupDevice>())
                .addData("total", 0)
                .addData("pages", 0);
    }

    /**
     * 根据分组添加设备信息
     *
     * @param data
     * @param group
     * @return
     */
    @PostMapping("/addGroupDevice")
    public Message addGroupDevice(String data, Integer group) throws UserException {
        if (ObjectUtil.isNull(group)) {
            throw new CustomException("请选择分组");
        }
        DeviceGroup deviceGroup = deviceGroupService.getById(group);
        return groupDeviceService.addGroupDevice(data, deviceGroup) ? Message.success() : Message.failed();
    }

    /**
     * 获取某个分组的详细信息 修改时用
     *
     * @param id
     * @return
     */
    @GetMapping("/getOneById")
    public DeviceGroupDTO getOneById(Integer id) {
        DeviceGroup deviceGroup = deviceGroupService.getById(id);
        DeviceGroupDTO deviceGroupDTO = getDeviceGroupDTO(deviceGroup);
        List<ListUserDTO> byGroupJoinUser = groupUserService.getByGroupJoinUser(id);
        if (!byGroupJoinUser.isEmpty()) {
            deviceGroupDTO.setUserList(byGroupJoinUser);
        }
        return deviceGroupDTO;
    }

    private DeviceGroupDTO getDeviceGroupDTO(DeviceGroup deviceGroup) {
        DeviceGroupDTO deviceGroupDTO = new DeviceGroupDTO();
        deviceGroupDTO.setId(deviceGroup.getId());
        deviceGroupDTO.setOrganization(deviceGroup.getOrganization());
        deviceGroupDTO.setName(deviceGroup.getName());
        deviceGroupDTO.setDesc(deviceGroup.getDesc());
        deviceGroupDTO.setTreejson(deviceGroup.getTreejson());
        deviceGroupDTO.setCreatetime(deviceGroup.getCreatetime());
        deviceGroupDTO.setUpdatetime(deviceGroup.getUpdatetime());
        deviceGroupDTO.setSelectedNode(deviceGroup.getSelectedNode());
        return deviceGroupDTO;
    }

    /**
     * 获取设备分组列表
     *
     * @return
     * @throws UserException
     */
    @GetMapping("/getGroupList")
    public Message getGroupList() throws UserException {
        String[] areaArr = currentUser().getArea();
        return Message.success().addData("data", deviceGroupService.list(new LambdaQueryWrapper<DeviceGroup>().in(DeviceGroup::getOrganization, areaArr)));
    }

    /**
     * 添加或者修改设备分组
     *
     * @param deviceGroupDTO
     * @return
     * @throws UserException
     */
    @PostMapping("/saveOrUpdateDeviceGroup")
    @Transactional
    public Message saveOrUpdateDeviceGroup(@RequestBody DeviceGroupDTO deviceGroupDTO) throws UserException {
        SysUser user = currentUser();
        deviceGroupDTO.setOrganization(user.getEnterprise());
        if (deviceGroupService.saveOrUpdate(deviceGroupDTO)) {
            groupUserService.remove(new LambdaQueryWrapper<GroupUser>().eq(GroupUser::getGroup, deviceGroupDTO.getId()));
            List<ListUserDTO> userList = deviceGroupDTO.getUserList();
            if (!userList.isEmpty()) {
                List<GroupUser> users = new ArrayList<>();
                for (ListUserDTO userDTO : userList) {
                    GroupUser groupUser = new GroupUser();
                    groupUser.setGroup(deviceGroupDTO.getId());
                    groupUser.setUser(userDTO.getValue());
                    users.add(groupUser);
                }
                groupUserService.saveBatch(users);
            }
            return Message.success();
        }
        return Message.failed();
    }
}